define(function (require, exports, module) {
    var myPub = require('./public');
    var myVideoPlay = require('./videoConfig');

    var coWindow = $(window);   //window
    var oWrap = $('.js_wrap');                      // wrap 部分
    var coContain = $('.js_contain');   //大盒子
    var coHeader = $('.js_headerBox');   //头部盒子
    var coFooter = $('.js_footer');      //页面底部
    var coAllCollection = $('.js_myCollection');   //装所有我的收藏的大盒子
    var oGoTop = $('.js_goTop');                    // 回到顶部
    var oSideBox = $('.js_sideBox');		        // 侧边按钮框
    var resizeTimer = null;
    // 获取产品数据的路径
    var collectDateUrl = '/video/getMyCollectionVideoList';

    var oMoreBtnBox = $('.js_moreBtnBox');          // 加载动画
    var oLoadingBtn = $('.js_loadingBtn');          // 加载动画
    var oerrPage = $('.js_errPage ');


    module.exports = {
        init: function (data, name) {
            //初始化事件
            myCollection.colInit();
            //滚动加载数据
            myCollection.scrollLoadData();
            //页面初始公
            coAjax.HistoryInit();

            //第一次进来的数据加载的最后的位置
            coAjax.endNum = coAjax.limitNum * coAjax.coPageArr;
            //console.log(coAjax.endNum);

            //页面进来动态获取数据
            coAjax.getMyCollection(function () {
                coAjax.HisScrollTop();
            });
            //myCollection.scrollLoadData();


            // 页面尺寸修改
            coWindow.on('resize', function () {
                if (resizeTimer) {
                    clearTimeout(resizeTimer)
                }
                resizeTimer = setTimeout(function () {
                    myCollection.colInit(true);
                }, 400);

            });

            //页面跳转时记录所需要的数据
            coWindow.unload(function () {
               coAjax.setSession();
            })

        }
    }

    var coAjax = {
        allCoData: null,      //请求回来的数据
        totalPageNum: 0,      //总数据的页数
        startNum: 0,         //数据加载的起始位置
        limitNum: 4,           //一次加载多少条数据
        endNum: 0,             //数据加载的结束位置
        coPageArr: 1,  //用于限定请求几次数据的限制
        coPageScroll: 0,  //保存滚动高度
        getMyCollection: function (fn) {   //数据请求的事件
            var $this = this;
            G_JSON_POST(collectDateUrl,{},function (data) {
                $this.allCoData = data.result;
                $this.totalPageNum = Math.ceil($this.allCoData.length / $this.limitNum);
                // console.log($this.totalPageNum);
                if (data.status == 200) {
                    if($this.allCoData.length == 0 ) return;
                    collectionHtml.allCollectHtml($this.allCoData, $this.startNum, $this.endNum, function () {
                        // console.log($this.endNum);
                        var oPlayerCenter = $(".js_playerCenter");
                        oPlayerCenter.each(function (i) {
                            // myVideoPlay.ddjVideo(oPlayerCenter.eq(i));
                            myVideoPlay.videoSet('js_videoPlay-' + coAjax.totalPageNum + '-' + i);
                        });
                        myCollection.connetProSwiper();
                    })
                    if (fn) fn();
                    data = null;
                }

            }, function () {

            }, function () {
                if($this.allCoData.length != 0){
                    oMoreBtnBox.show();
                    if($this.totalPageNum <= $this.coPageArr) {
                        oLoadingBtn.hide().eq(0).show();
                    }
                    $('html').removeClass('Height100')
                }
                else {
                    oerrPage.show();
                    oWrap.hide();
                    $('html').addClass('Height100')
                }
            })

        },
        //历史数据定位
        HistoryInit: function (fn1, fn2) {
            var $this = this;
            if (sessionStorage.getItem("coPageScroll") != null) {
                //初始化进来先获取缓存中的数据
                $this.getSessionData();
                if (fn1) fn1();
            } else {
                if (fn2) fn2();
            }

        },
        //历史滚动高度
        HisScrollTop: function () {
            if (sessionStorage.getItem('coPageScroll') != null) {
                //重新进来后加载到之前记录的位置
                var pageScrollNum = sessionStorage.getItem("coPageScroll");
                coWindow.scrollTop(parseInt(pageScrollNum));
            }
        },
        //   设置历史定位
        setSession: function () {
            var $this = this;
            //设置要存在缓存中的数据
            sessionStorage.setItem("coPageArr", $this.coPageArr);
            sessionStorage.setItem("coPageScroll", $this.coPageScroll);
        },
        //    记录数据历史数据
        getSessionData: function () {
            var $this = this;
            if (sessionStorage.getItem("coPageScroll") != null) {
                //获取缓存里的数据
                var pageNum = sessionStorage.getItem("coPageArr");
                var pageScrollNum = sessionStorage.getItem("coPageScroll");
                //重新设置,让第二次进来以之前的记录加载
                $this.coPageArr = parseInt(pageNum);
                $this.coPageScroll = parseInt(pageScrollNum);
            }
        }
    }

    //对象事件
    var myCollection = {
        time_Scroll : null,
        oSlideAdsScroll: [],
        colInit: function (bOff) {  //初始化事件
            if (bOff) {
                coContain.css({
                    'padding-top': coHeader.outerHeight(true),
                    'padding-bottom': coFooter.outerHeight(true)
                });
            }
            oSideBox.stop().animate({'right': '-3.5rem'}, 300);
        },

        //关联商品使用swiper的方法
        connetProSwiper: function () {
            var _this = this;
            var oHScrollBox = $('.js_WScroll');
            oHScrollBox.each(function (i) {
                if(_this.oSlideAdsScroll[i] === undefined) {
                    _this.oSlideAdsScroll[i] = oHScrollBox.eq(i).swiper({
                        freeMode: true,
                        freeModeMomentumRatio: 0.5,
                        lazyLoading: true,
                        watchSlidesProgress: true,
                        watchSlidesVisibility: true,
                        slideClass: 'slide-HScroll',
                        slidesPerView: 'auto',
                        observer: true,
                        observeParents: true,
                        onSlideChangeEnd: function (swiper) {
                        }
                    });
                }
            });
            // 设置app产品跳转链接
            myPub.JudgeAppHref(oHScrollBox.find('.js_appHref'));
        },
        scrollLoadData: function () {  //滚动加载数据
            var $this = this;
            var minHeight = 300;

            coWindow.on('scroll', function (event) {
                var nowScrollTop = $(this).scrollTop();
                clearTimeout($this.time_Scroll);
                $this.time_Scroll = setTimeout(function () {
                    coAjax.coPageScroll = nowScrollTop;
                    if (oWrap[0].scrollHeight - nowScrollTop - oWrap.height() < minHeight) {
                        //如果无数据
                        if (coAjax.allCoData == null) {
                            return
                        }

                        //判断是否翻到最后
                        if (coAjax.coPageArr >= coAjax.totalPageNum ) {
                            coAjax.allCoData = null;
                            oLoadingBtn.hide().eq(0).show();
                            return;
                        }
                        //每加载一次,所翻的页面+1
                        coAjax.coPageArr++;
                        //加载了一次就更新数据加载开始的位置
                        coAjax.startNum = coAjax.endNum;
                        //加载了次后更新数据加载结束的位置
                        coAjax.endNum = coAjax.limitNum * coAjax.coPageArr;

                        //滚动到那高度再拼接数据
                        collectionHtml.allCollectHtml(coAjax.allCoData, coAjax.startNum, coAjax.endNum);
                    }
                }, 150)
            })
        }

    }


    //拼接的html
    var collectionHtml = {
        allCollectHtml: function (data, startNum, endNum, fn) { //整一个收藏内容的文本
            var $this = this;
            var shtml = '';
            // console.log(data);
            for (var i = startNum; i <endNum && i<data.length; i++) {
                shtml +=
                    '<div class="myCollectionCon backWhite js_myCollectionOne a11">' +
                        $this.topAndVideoHtml(data[i], i) +
                        $this.connectProBox(collectionHtml.connectProHtml(data[i].videoGoodsList)) +
                    '</div>';
            }
            coAllCollection.append(shtml);
            if (fn) fn();
        },
        connectProHtml: function (data) { //所关联商品的内容
            var shtmlBox = '';
            var shtml = '';
            if(data!=null){
                for (var i = 0; i < data.length; i++) {
                    shtml +=
                        '<div class="slide-HScroll eachConnectPro leftLineBox">' +
                        '    <a class="eachConnectProduct HBox js_appHref"  _href="'+data[i].goodsSn+'">' +
                        '        <div class="leftProImg">' +
                        '            <figure>' +
                        '                <img class="swiper-lazy"  data-src="'+HTTP_IMAGE_URL+data[i].image+ smallImgArg200 +'" src="/static_v4/image/loadImg.jpg"  alt="">'+
                        '            </figure>' ;
                    if(data[i].firstGueeImagePath!=null && data[i].firstGueeImagePath!=''){
                        shtml += '<img src="'+BASE_URL+data[i].firstGueeImagePath+'"alt="" class="quanpei_video"/>';
                    };
                    shtml +=  '  </div>' +
                        '        <div class="rightProCon Bflex1 VBox">' +
                        '            <div class="rightProConTop Bflex1">' +
                        '                <h6 class="showOneLine">'+data[i].goodsName+'</h6>' +
                        '            </div>' +
                        '            <div class="rightProConBot">' +
                        '                <p><i>￥</i><span>'+data[i].salePrice+'</span></p>' +
                        '            </div>' +
                        '        </div>' +
                        '    </a>' +
                        '</div>';
                }

            }
            return shtml;
        },
        connectProBox: function (shtml) {
            var shtmlBox = '';

            shtmlBox =
                '<div class="connectProducts connectTriangle">' +
                '    <div class="allConnectPro swiper-container js_WScroll">' +
                '        <div class="swiper-wrapper swrap-HScroll HBox">' +
                shtml +
                '         </div>' +
                '    </div>' +
                '</div>';
            return shtmlBox;
        },
        topAndVideoHtml: function (data, iNow) {
            //一个收藏内容的头部和视频部分的内容
            var shtml = '';
            var _supportAct='';

            var labels=data.labelsList;
            var lis='';
            for(var i=0; i<labels.length ; i++){
                lis+='<li>'+labels[i]+'</li> ';
            };
            shtml +=
                '<div class="collectionConTop">' +
                '    <h2>'+ data.videoName +'</h2>' +
                '    <div class="cancleCollectionBox HBox">' +
                '       <div class="goodIdeaLeft Bflex1"> ' +
                '           <ul>'+
                               lis +
                '          </ul> '+
                '       </div>';

            if (data.isSupport == true){
                _supportAct = 'active';
            }

            shtml+=
                '        <div class="cancleColRight HBox ">' +
                '            <p class="greatNum js_getGreatNum HBox '+ _supportAct +'" videoId="'+data.id+'">' +
                '               <i class="iconStyle icon-goods"></i>' +
                '               <span class="verMid js_greatNum allGoodsNum">'+data.supportCount+'</span>' +
                '           </p>' +
                '            <p class="rightCancle js_cancleCollect " videoId="'+data.id+'"><span>取消收藏</span></p>' +
                '        </div>' +
                '    </div>' +
                '</div>'+
            collectionHtml.videoHtml(data, iNow);
            return shtml;
        },
        videoHtml: function (data, iNow) {
            var shtml = '';
            var videoName = data.videoName;
            // var videoNameTip = '惊天大逆转! 隐藏的实力即将爆发!';
            var bgImg = HTTP_IMAGE_URL+data.videoImgPath;
            var videoSource = data.videoPath;
            shtml =

                '<section class="playVideo js_playVideo">'+
                '    <div class="player-center js_playerCenter">'+
                '        <video id="js_videoPlay-'+ coAjax.totalPageNum + '-' + iNow + '" class="video-js my-video js_my-video" height="100%" width="100%" '+
                '               controls '+
                '               preload="none" '+
                '               playsinline="true" '+
                '               webkit-playsinline="true" '+
                '               x-webkit-airplay="allow" '+
                '               poster="'+ bgImg +'" '+
                '               videoId="'+ data.id +'" '+
                '               data-setup="{}"> '+
                '            <source src="'+ videoSource +'" type="video/mp4">'+
                '            <source src="'+ videoSource +'" type="video/ogg">'+
                '            <source src="'+ videoSource +'" type="video/webm">'+
                '        </video>' +
                '    </div>'+

                '    <div class="player-layer js_player-layer" >'+
                '        <div class="player-video-name">'+
                '            <h3>'+ videoName +'</h3>'+
                '        </div>'+
                // '        <div class="player-video-detail">'+
                // '            <a href="video-videoDetail.html">'+
                // '                <span>详情</span><span class="iconStyle icon-chevron-right"></span>'+
                // '            </a>'+
                // '        </div>'+
                '    </div>'+

                '    <div class="player-repeat js_player-repeat" style="display: none">'+
                '        <button type="button" class="btnStyle replayBtn js_replayBtn">'+
                '            <span class="iconStyle icon-redo"></span>'+
                '            <span>重新播放</span>'+
                '        </button>'+
                '    </div>'+
                '</section>';

            return shtml;

        }
    }
})